package com.beidouapp.common.util;

import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.PropertyFilter;

public class JSONUtils
{

	public static JSONObject convert2Obj(Object sourceObject)
	{
		JsonConfig config = new JsonConfig();
		config.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
		config.setJsonPropertyFilter(new PropertyFilter()
		{
			@Override
			public boolean apply(Object paramObject1, String paramString, Object paramObject2)
			{
				if (paramObject2 == null)
				{
					return true;
				}
				else
				{
					return false;
				}
			}

		});
		JSONObject jsonObject = JSONObject.fromObject(sourceObject, config);
		return jsonObject;
	}

	public static JSONArray convert2Arr(List<?> sourceObjects)
	{

		JsonConfig config = new JsonConfig();
		config.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
		config.setJsonPropertyFilter(new PropertyFilter()
		{
			@Override
			public boolean apply(Object paramObject1, String paramString, Object paramObject2)
			{
				if (paramObject2 == null)
				{
					return true;
				}
				else
				{
					return false;
				}
			}

		});
		JSONArray jsonArray = JSONArray.fromObject(sourceObjects, config);
		return jsonArray;
	}

	public static class JsonDateValueProcessor implements JsonValueProcessor
	{
		@Override
		public Object processArrayValue(Object value, JsonConfig jsonConfig)
		{
			return process(value);
		}

		@Override
		public Object processObjectValue(String key, Object value, JsonConfig jsonConfig)
		{
			return process(value);
		}

		private Object process(Object value)
		{
			if (value instanceof Date)
			{
				return ((Date) value).getTime();
			}
			return value;
		}

	}
}
